var revenueApi = require('../../script/revenue.js');
var publicApi = require('../../script/public.js');
var config = require('../../script/config.js');
import {
  parseTime
} from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: config.baseUrl,
    DETAIL_ID: '',
    OrderInfo: null,
    imgList: [], // 显示的图片列表
    imgFileList: [], // 上传的图片文件列表
    videoFileList: [], // 上传的视频文件列表
    show: false,
    steps: [],
    stepActive: 0,
    datePop: false,
    reasonPop: false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    Reason: '',
    AuditType: [],
    ExamineForm: {
      Result: '1',
      Reason: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.GetPCodes();
    if (options) {
      this.setData({
        DETAIL_ID: options.id,
      });
      this.getDetail();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // GetPCodes() {
  //   publicApi.GetPCodes({
  //     keys: ['AuditType'],
  //   }).then(res => {
  //     this.setData({
  //       AuditType: res.data.AuditType,
  //     })
  //   }) 
  // },
  getDetail() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    const params = {
      Data: JSON.stringify({
        DETAIL_ID: this.data.DETAIL_ID,
      }),
    }
    revenueApi.ViewCheckDetail(params).then(res => {
      if (res.code === 200) {
        const info = res.data;
        info.PLAN_START_DATE_STR = info.PLAN_START_DATE.slice(0, 10);
        info.PLAN_END_DATE_STR = info.PLAN_END_DATE.slice(0, 10);
        let steps = [];
        if (info.Logs && info.Logs.length > 0) {
          steps = info.Logs.map(item => {
            return {
              text: item.Log,
              desc: item.Date_Time
            }
          })
        }
        this.setData({
          OrderInfo: info,
          steps,
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'none',
          duration: 1500
        });
      }
    }).finally(() => {
      wx.hideLoading();
    })
  },
  showMore() {
    this.setData({
      show: !this.data.show
    })
  },
  /************* 取消计划 **************/
  CancelPlan() {
    wx.showModal({
      title: '请确认是否取消计划？',
      content: '提示：取消计划后，可针对本户重新计划',
      success: (res) => {
        if (res.confirm) {
          const params = {
            Data: JSON.stringify({
              TaskDetailNos: this.data.AUDIT_ID,
              PlanDate: '', // 当时间为空时，代表取消计划
            })
          }
          revenueApi.UpdateTaskPlan(params).then(res => {
            if (res.code === 200) {
              wx.showToast({
                title: '取消成功！',
                icon: 'none',
                duration: 1500,
                success: () => {
                  wx.navigateBack();
                }
              });
            } else {
              wx.showToast({
                title: res.info,
                icon: 'none',
                duration: 2000
              });
            }
          })
        }
      }
    })
  },
  /************* 取消计划 **************/
  toAudit() {
    wx.navigateTo({
      url: "/packageAudit/do-audit/do-audit?id=" + this.data.DETAIL_ID
    })
  },

  /************* 申请延期 **************/
  showDate() {
    this.setData({
      datePop: true,
    });
  },
  closePop() {
    this.setData({
      datePop: false,
      reasonPop: false,
      examinePop: false
    });
  },
  onInput(e) {
    this.setData({
      currentDate: e.detail,
    });
  },
  onConfirm(e) {
    this.setData({
      datePop: false,
    });
    const timestamp = this.data.currentDate;
    if (timestamp < new Date(this.data.OrderInfo.END_DATE).getTime()) {
      wx.showToast({
        title: '任务未超期，选择日期在计划日期内',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    this.setData({
      datePop: false,
      reasonPop: true,
    })
  },
  reasonChange(e) {
    this.setData({
      Reason: e.detail.value
    });
  },
  ReasonCancel() {
    this.setData({
      Reason: '',
      reasonPop: false
    });
  },
  ReasonConfirm() {
    if (this.data.Reason == '') {
      wx.showToast({
        title: '请输入延期原因',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    this.setData({
      reasonPop: false
    });
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    const params = {
      Data: JSON.stringify({
        TaskDetailNos: this.data.DETAIL_ID,
        PlanDate: parseTime(this.data.currentDate),
        Reason: this.data.Reason
      }),
    }
    revenueApi.DeferTaskPlan(params).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        wx.showToast({
          title: res.info,
          icon: 'none',
          duration: 2000,
          success: () => {
            wx.navigateBack();
          }
        });
      } else {
        wx.showToast({
          title: res.info,
          icon: 'none',
          duration: 2000
        });
      }
    }).catch(_err => {
      wx.hideLoading();
    });
  },
  /************* 申请延期 **************/

  /************* 审核相关 **************/
  toExamone() {
    this.setData({
      examinePop: true
    });
  },
  ExamineResultChange(e) {
    this.setData({
      "ExamineForm.Result": e.detail.value
    });
  },
  ExamineReasonChange(e) {
    this.setData({
      "ExamineForm.Reason": e.detail.value
    });
  },
  CloseExamine() {
    this.setData({
      examinePop: false
    });
  },
  DoExamine() {
    if (this.ExamineForm.Result === '2' &&
      this.ExamineForm.Result.Reason === '') {
      wx.showToast({
        title: '不同意原因不能为空！',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.showLoading({
      title: '提及中...',
      mask: true
    });
    const params = {
      OrderID: this.data.AuditInfo.OrderID,
      HandleWay: 1
    }
    let func = "";
    if (this.data.AuditInfo.AuditType === 2) {
      func = 'Examine';
      params.TempResult = this.data.AuditInfo.TempResult;
      params.ExamReason = this.data.AuditInfo.TempReason;
    } else {
      func = 'UpdateOrderProcedure';
      params.ProcedureCode = this.data.AuditInfo.ProcedureCode;
      params.ProcedureStatus = this.data.AuditInfo.AuditResult === "1" ? 2 : 8;
      params.HandlerResult = this.data.AuditInfo.AuditResult === "2" ? this.data.AuditInfo.AuditReason : "";
    }
    http[func](params).then(res => {
      // wx.hideLoading();
      if (res.code === 200) {
        const _this = this;
        _this._refreshData();
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(() => {
              wx.navigateBack();
            }, 2000)
          }
        });
      } else {
        wx.showToast({
          icon: 'none',
          title: res.info,
          duration: config.toast.duration
        });
      }
    }).catch(_err => {
      // wx.hideLoading();
    });
  },
  /************* 审核相关 **************/

  /************* 打电话/导航 **************/
  Call: function (e) {
    var pnonenum = e.currentTarget.dataset.phone;
    if (pnonenum == null || pnonenum == '') {
      wx.showToast({
        title: '暂无电话号码',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    var res = wx.getSystemInfoSync();
    if (res.platform == 'ios') {
      wx.makePhoneCall({
        phoneNumber: pnonenum
      });
    } else {
      wx.showActionSheet({
        itemList: [pnonenum, '呼叫'],
        success: function (res) {
          if (res.tapIndex == 1) {
            wx.makePhoneCall({
              phoneNumber: pnonenum
            })
          }
        }
      })
    }
  },
  toMap(e) {
    var order = e.currentTarget.dataset.order;
    if (order.Lat == null || order.Lat == 0 || order.Lng == null || order.Lng == 0) {
      wx.showModal({
        title: '位置上报',
        content: '当前用户无位置信息，是否立即上报？',
        success: (res) => {
          if (res.confirm) {
            wx.chooseLocation({
              success: (res) => {
                const params = {
                  Data: JSON.stringify({
                    UserCode: order.UserCode,
                    Lat: res.data.latitude,
                    Lng: res.data.longitude,
                  })
                }
                revenueApi.UpdateConsPosition(params).then(res => {
                  if (res.code === 200) {
                    wx.showToast({
                      title: '上报成功！',
                      icon: 'none',
                      duration: 1500
                    });
                    this._refreshData();
                  }
                })
              }
            });
          }
        }
      })
    } else {
      wx.openLocation({
        latitude: order.Lat,
        longitude: order.Lng,
        address: info.WATER_ADDR,
        scale: 18
      })
      // wx.getLocation({
      //   type: 'gcj02', //返回可以用于 wx.openLocation 的经纬度
      //   success(res) {
      //     const latitude = res.latitude
      //     const longitude = res.longitude
      //     wx.openLocation({
      //       latitude,
      //       longitude,
      //       address: info.Address,
      //       scale: 18
      //     })
      //   }
      // })
    }
  }, 
  /************* 打电话/导航 **************/
})